package com.leizi.igym.controller.admin;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.leizi.igym.constant.MemberConstant;
import com.leizi.igym.domain.Member;
import com.leizi.igym.dto.MemberAddDTO;
import com.leizi.igym.dto.MemberDTO;
import com.leizi.igym.dto.MemberPageQueryDTO;
import com.leizi.igym.enums.FileUploadBizEnum;
import com.leizi.igym.enums.ReturnCodeEnum;
import com.leizi.igym.exception.BusinessException;
import com.leizi.igym.manager.CosManager;
import com.leizi.igym.resp.PageResult;
import com.leizi.igym.resp.Result;
import com.leizi.igym.service.MemberService;
import com.leizi.igym.utils.COSUtils;
import com.leizi.igym.utils.ThrowUtils;
import com.leizi.igym.vo.MemberVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.util.List;
import java.util.Objects;

/**
 * @Author: leizi0110
 * @CreateTime: 2024-04-03  18:01
 * @Description:
 */

@RestController("adminMemberController")
@RequestMapping("/admin/member")
@Tag(name = "管理端-会员相关接口")
@Slf4j
public class MemberController {

    @Resource
    private MemberService memberService;
    @Resource
    private CosManager cosManager;


    @Operation(summary = "管理端：分页查询会员信息")
    @GetMapping("/page")
    public Result<PageResult> getMemberByPage(MemberPageQueryDTO dto) {
        log.info("管理端正在分页查询会员信息，：查询参数：{}", dto);
        ThrowUtils.throwIf(Objects.isNull(dto), ReturnCodeEnum.PARAMS_ERROR);
        long current = dto.getCurrent();
        long size = dto.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 50, ReturnCodeEnum.PARAMS_ERROR);

        // 分页查询
        Page<Member> page = memberService.page(new Page<>(current, size),
                memberService.getQueryWrapper(dto));
        List<MemberVO> memberVOPage = memberService.getMemberVOPage(page);

        // 封装到PageResult中
        PageResult pageResult = PageResult.builder().total(page.getTotal())
                .records(memberVOPage)
                .build();
        return Result.ok(pageResult);
    }

    @Operation(summary = "管理端：根据id查询会员信息")
    @GetMapping("/{id}")
    public Result<MemberVO> getMemberById(@PathVariable("id") Long id) {
        log.info("管理端正在根据id查询会员信息，：查询会员id：{}", id);
        return Result.ok(memberService.getMemberById(id));
    }

    @Operation(summary = "管理端：新增会员信息")
    @PostMapping
    public Result<Boolean> addMember(@RequestBody MemberAddDTO dto) {
        log.info("管理端正在新增会员信息，：新增会员：{}", dto);
        ThrowUtils.throwIf(Objects.isNull(dto), ReturnCodeEnum.PARAMS_ERROR);
        ThrowUtils.throwIf(!memberService.saveMember(dto), ReturnCodeEnum.SYSTEM_ERROR, "新增会员失败！");
        return Result.ok(true);
    }

    @Operation(summary = "管理端：删除会员信息")
    @DeleteMapping("{id}")
    public Result<Boolean> deleteMemberById(@PathVariable("id") Long id) {
        log.info("管理端正在删除会员信息，：删除会员id：{}", id);
        ThrowUtils.throwIf(Objects.isNull(id) || id < 0, ReturnCodeEnum.PARAMS_ERROR);
        ThrowUtils.throwIf(!memberService.removeById(id), ReturnCodeEnum.SYSTEM_ERROR, "删除会员失败！");
        return Result.ok(true);
    }

    @Operation(summary = "管理端：批量删除会员信息")
    @DeleteMapping("batch")
    public Result<Boolean> deleteMemberBatch(@RequestBody List<Long> ids) {
        log.info("管理端正在删除会员信息，：删除会员id：{}", ids);
        ThrowUtils.throwIf(Objects.isNull(ids) || ids.size() == 0, ReturnCodeEnum.PARAMS_ERROR);
        ThrowUtils.throwIf(!memberService.removeMemberBatch(ids), ReturnCodeEnum.SYSTEM_ERROR, "批量删除会员失败！");
        return Result.ok(true);
    }


    @Operation(summary = "管理端：修改会员信息")
    @PutMapping("/{id}")
    public Result updateMember(@PathVariable("id") Long id,
                            @RequestBody MemberDTO dto) {
        log.info("管理端正在修改会员信息，会员id为：{},修改信息为：{}", id, dto);
        if (Objects.isNull(dto) || id == null || id <= 0 || !id.equals(dto.getId())) {
            throw new BusinessException(ReturnCodeEnum.PARAMS_ERROR);
        }
        MemberVO dbMember = memberService.getMemberById(id);
        String dbMemberAvatar = dbMember.getAvatar();
        String avatar = dto.getAvatar();
        if (dbMemberAvatar.contains(FileUploadBizEnum.MEMBER_AVATAR.getValue()) &&
                !avatar.equals(dbMemberAvatar)) {
            cosManager.deleteObject(COSUtils.parseFileName(FileUploadBizEnum.MEMBER_AVATAR,dbMemberAvatar));
        }
        Member member = new Member();
        BeanUtils.copyProperties(dto, member);
        member.setCreateTime(dbMember.getCreateTime());
        return Result.ok(memberService.updateMemberInAdmin(member));

    }
}
